package edu.upc.fib.lamsandroid.server.web;

import edu.upc.fib.lamsandroid.server.api.model.User;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpSession;

/**
 * Created with IntelliJ IDEA.
 * User: TXABI
 * Date: 24/03/13
 * Time: 9:56
 * To change this template use File | Settings | File Templates.
 */

public class SessionContainerImpl implements SessionContainer {

    private static final String ATTR_USER = "lamspfc__user";

    @Override
    public User getSessionUser() {
        HttpSession session = getSession();

        if(session != null) {
            return (User) session.getAttribute(ATTR_USER);
        }

        return null;
    }

    @Override
    public void setSessionUser(User user) {
        HttpSession session = getSession();

        if(session != null) {
            session.setAttribute(ATTR_USER, user);
        }
    }

    private HttpSession getSession() {
        ServletRequestAttributes attr = (ServletRequestAttributes) RequestContextHolder.currentRequestAttributes();
        if(attr != null) {
            if(attr.getRequest() != null) {
                return attr.getRequest().getSession(true);
            }
        }

        System.out.println("!!! CANNOT ACCESS SESSION !!!");

        return null;
    }
}
